import axios,{AxiosRequestConfig,AxiosResponse} from "axios"
import useStore from "@/store"
import router from "@/router"
import { ElNotification } from 'element-plus'

const request = axios.create({
    baseURL: import.meta.env.VITE_APP_BASE_API,
    timeout:6000,
    headers: { 'Content-Type': 'application/json;charset=utf-8' }
})

request.interceptors.request.use((config:any)=>{
    if(!config.headers){
        throw new Error(
            `Expected 'config' and 'config.headers' not to be undefined`
          );
    }
    const { user } = useStore();
    if(user.token){
        config.headers.token = user.token
    }
    return config
},error=>{
    return Promise.reject(error)
})

request.interceptors.response.use((res:AxiosResponse)=>{
    if(res.data.code!==200){
      ElNotification({
        title: '操作失败',
        message: res.data.msg,
        duration: 2000,
        type:"warning"
      })
    }
    return res
},error=>{
  console.log(error);
  
  if(error.response.data.code=='A0230'){
    window.localStorage.clear()
    router.push('/login')
  }
    return Promise.reject(error)
})

export default request